
from question_classifier import *
from question_parser import *
from answer_search import *
from flask import Flask, request, session, send_file


app = Flask(__name__,static_url_path='')
app.config['SECRET_KEY'] = 'qakb123456'
'''问答类'''
class ChatBotGraph:
    def __init__(self):
        # question_classifier.py里的 QuestionClassifier:
        self.classifier = QuestionClassifier()
        #question_paser.py里的 QuestionPaser:
        self.parser = QuestionPaser()
        #answer_search.py里的AnswerSearcher:
        self.searcher = AnswerSearcher()
        self.classify = {
            "diseases":  ["{}是什么","{}有什么症状","{}的原因","{}的并发症","{}能吃什么","{}不能吃什么","{}吃什么药","{}怎么预防","{}多长时间会好","{}怎么治疗","{}多大概率能治好","{}的易感人群","{}的检查项目","{}属于什么科"],
            "food": ["吃{}有什么好处"],
            "drug": ["吃{}治疗什么"],
            "symptom": ["为什么会{}"]
        }
        # self.history_entity = None
        # self.disease_classify = ["{}是什么","{}有什么症状","{}的原因","{}的并发症","{}能吃什么","{}不能吃什么","{}吃什么药","{}怎么预防","{}多长时间会好","{}怎么治疗","{}多大概率能治好","{}的易感人群","{}的检查项目","{}属于什么科"]
        # self.food_classify = ["吃{}有什么好处"]
        # self.drug_classify = ["吃{}治疗什么"]
        # self.symptom_classify = ["为什么会{}"]
    def chat_main(self, sent,session):
        answer = '您好，我是医药智能助理，希望可以帮到您。目前问题还无法回答，请用更简洁的话来问哟~'
        res_classify = self.classifier.classify(sent,session)
        print("res_classify11:", res_classify)
        print("session[entity]:",session['entity'])
        if not res_classify:
            if not session:
                return answer
            else:
                type = list(session['entity'].values())[0]
                entity = list(session['entity'].keys())[0]
                print("entity22:",entity)
                result = ['您可以试试这么问我：']
                for (index,item) in enumerate(self.classify[type]):
                    result.append(str(index+1)+". "+item.format(entity))
                return '<br>'.join(result)
        res_sql = self.parser.parser_main(res_classify)
        final_answers = self.searcher.search_main(res_sql)
        if not final_answers:
            return answer
        else:
            return '<br>'.join(final_answers)

handler = ChatBotGraph()
@app.route('/',methods=['GET'])
def home():
    return send_file("static/index.html")

@app.route('/input',methods=['POST'])
def hello_world():

    text = request.form.get("text")

    return {'send':'you','msg':handler.chat_main(text,session)}
if __name__ == '__main__':
    app.run(port=10086)
    # handler = ChatBotGraph()
    # while 1:
    #     question = input('用户:')
    #     answer = handler.chat_main(question)
    #     print('小勇:', answer)

